<script>
export default {
  // 全局数据对象，用于存储应用运行时的全局变量
  globalData: {
    pre_url: "", // 前置URL，通常用于拼接API请求的基础URL
    static_url: "", // 前置URL，通常用于拼接API请求的静态资源
    api_url: "", // API请求的URL
    baseurl: "", // 基础URL，通常用于拼接API请求的完整URL
    session_id: "", // 会话ID，用于用户会话管理
    aid: 0, // 应用ID，标识当前应用
    mid: 0, // 用户ID，标识当前用户
    pid: 0, // 推广ID，用于推广链接中的参数
    pmid: 0, //分享人的id，用于记录谁分享过来的链接
    needAuth: 0, // 是否需要授权，0表示不需要，1表示需要
    platform: "wx", // 当前平台，默认为微信小程序
    platform2: "", // 辅助平台信息，用于区分不同平台
    isdouyin: 0, // 是否为抖音平台，0表示不是，1表示是
    sysset: [], // 系统设置，存储系统配置信息
    indexurl: "/pages/index/index", // 首页URL
    menudata: [], // 菜单数据，存储应用的菜单信息
    menu2data: [], // 二级菜单数据
    currentIndex: -1, // 当前选中的菜单索引
    initdata: {}, // 初始化数据，存储应用初始化时的数据
    memberinfo: {}, //用户信息
    nextlevelinfo: {}, //可以购买的等级信息
    kefuInfo: {}, //客服信息
    textset: [], // 文本设置，存储应用的文本配置
    isinit: false, // 是否已经初始化，false表示未初始化，true表示已初始化
    socketOpen: false, // WebSocket连接是否已打开
    socket_token: "", // WebSocket连接的令牌
    socketMsgQueue: [], // WebSocket消息队列，存储待发送的消息
    socketConnecttimes: 0, // WebSocket连接尝试次数
    socketInterval: null, // WebSocket心跳间隔
    scene: 0, // 场景值，用于区分不同的场景
    homeNavigationCustom: 0, // 首页导航栏自定义设置
    usercenterNavigationCustom: 0, // 用户中心导航栏自定义设置
    navigationBarBackgroundColor: "#ffffff", // 导航栏背景颜色
    navigationBarTextStyle: "black", // 导航栏文字颜色
    rewardedVideoAd: {}, // 激励视频广告对象
    seetype: "", // 查看类型，用于区分不同的查看场景
    giftdata: [],
    gift_is_secret: false,
    gift_num: 1,
    gift_currentTab: 0,
    pro_ids: [],
    vip_info: {}, //vip卡信息
    indexTab: [], //tab组件排序
    tabList: [], //tab组件数组
    isTabCanTop: "", //tab组件是否可以吸顶(首页)
    ggStatus: true, //首页广告关闭状态
    videolive: {
      type: 0,
      list: [],
    }, //视频流数据
    draftData: {
      allTab: 0,
      title: null,
      content: null,
      imageList: [],
      friend_mids: null,
      video_url: {},
    }, //发布作品数据
    commerce_mid: 0, //带货用户id
    commerce_type: 0, //带货类型
  },

  // 应用启动时的生命周期函数
  onLaunch: function (options) {
    console.log("启动参数：", options);

    // try {
    // 	// 获取启动时的场景值
    // 	const launchOptions = uni.getLaunchOptionsSync().scene;
    // 	// 1011-扫描二维码
    // 	if (launchOptions === 1001) {
    // 		if (uni.getLaunchOptionsSync().query.scene) {
    // 			let sr = this.parseCustomString(uni.getLaunchOptionsSync().query.scene);
    // 			if (sr) {
    // 				if (sr.pmid) {
    // 					this.globalData.pmid = sr.pmid;
    // 				}
    // 			}
    // 		}
    // 	}
    // } catch (error) {
    // }

    // 获取扩展配置信息
    var extConfig = uni.getExtConfigSync ? uni.getExtConfigSync() : {};
    console.log("extConfig", extConfig);

    // 如果扩展配置中存在aid，则使用扩展配置中的信息
    if (extConfig && extConfig.aid) {
      this.globalData.aid = extConfig.aid;
      this.globalData.pre_url = extConfig.baseurl;
      this.globalData.homeNavigationCustom =
        extConfig.homeNavigationCustom || 0;
      this.globalData.usercenterNavigationCustom =
        extConfig.usercenterNavigationCustom || 0;
      this.globalData.navigationBarBackgroundColor =
        extConfig.navigationBarBackgroundColor || "#ffffff";
      this.globalData.navigationBarTextStyle =
        extConfig.navigationBarTextStyle || "black";
    } else {
      // 否则使用默认的站点信息
      var siteInfo = require("./siteinfo.js");
      this.globalData.aid = siteInfo.uniacid;

      // 在H5环境下，从URL中解析出uniacid
      // #ifdef H5
      var url = window.location.href.split("#")[0];
      var urlArr = url.split("/");
      var htmlname = urlArr[urlArr.length - 1];
      var uniacid = htmlname.replace(".html", "");
      console.log(uniacid);
      var reg = /^[0-9]+$/;
      if (uniacid && reg.test(uniacid)) {
        this.globalData.aid = uniacid;
      }
      // #endif

      this.globalData.pre_url = siteInfo.siteroot;
      this.globalData.static_url =
        siteInfo.siteroot + "/aid/" + siteInfo.uniacid;
      this.globalData.api_url = siteInfo.apiroot;
      this.globalData.homeNavigationCustom = siteInfo.homeNavigationCustom || 0;
      this.globalData.usercenterNavigationCustom =
        siteInfo.usercenterNavigationCustom || 0;
      this.globalData.navigationBarBackgroundColor =
        siteInfo.navigationBarBackgroundColor || "#ffffff";
      this.globalData.navigationBarTextStyle =
        siteInfo.navigationBarTextStyle || "black";
    }

    // 拼接基础URL
    this.globalData.baseurl = this.globalData.pre_url + "/api/";
    // 从本地存储中获取session_id
    this.globalData.session_id = uni.getStorageSync("session_id");

    // 解析启动参数
    var opts = this.getopts(options.query);
    if (opts && opts.pid) {
      this.globalData.pid = opts.pid;
      uni.setStorageSync("pid", this.globalData.pid);
    }
    // 处理其他启动参数
    if (opts && opts.mid) {
      console.log(opts.mid, 88888);
    }
    console.log(opts, "opts**********************************");

    if (opts && opts.uid) {
      this.globalData.uid = opts.uid;
    }

    // 处理seetype参数
    if (options && options.query && options.query.seetype) {
      this.globalData.seetype = options.query.seetype;
    } else {
      if (opts && opts.seetype) {
        this.globalData.seetype = opts.seetype;
      }
    }

    // 根据平台类型设置platform和platform2
    // #ifdef APP-PLUS
    this.globalData.platform = "app";
    var app = this;
    uni.getSystemInfo({
      success: function (res) {
        app.globalData.platform2 = res.platform;
      },
    });
    // #endif

    // #ifdef H5
    this.globalData.platform = "h5";
    if (navigator.userAgent.indexOf("MicroMessenger") > -1) {
      this.globalData.platform = "mp";
    }
    // #endif

    // #ifdef MP-WEIXIN
    this.globalData.platform = "wx";
    this.checkUpdateVersion(); // 检查微信小程序版本更新
    // #endif

    // #ifdef MP-ALIPAY
    this.globalData.platform = "alipay";
    // #endif

    // #ifdef MP-BAIDU
    this.globalData.platform = "baidu";
    // #endif

    // #ifdef MP-TOUTIAO
    this.globalData.platform = "toutiao";
    var sysinfo = tt.getSystemInfoSync();
    if (sysinfo.appName == "Douyin") {
      this.globalData.isdouyin = 1;
    }
    // #endif

    // #ifdef MP-QQ
    this.globalData.platform = "qq";
    // #endif

    console.log("平台:", this.globalData.platform);

    // 初始化WebSocket连接
    //#ifndef MP-TOUTIAO
    var app = this;
    uni.onSocketOpen(function (res) {
      app.globalData.socketOpen = true;
      // 发送消息队列中的消息
      for (var i = 0; i < app.globalData.socketMsgQueue.length; i++) {
        app.sendSocketMessage(app.globalData.socketMsgQueue[i]);
      }
      app.globalData.socketMsgQueue = [];
    });

    // 监听WebSocket消息
    uni.onSocketMessage(function (res) {
      console.log("收到服务器内容：" + res.data);
      try {
        var data = JSON.parse(res.data);
        app.handleSocketMessage(data);
        var needpopup = true;
        var pages = getCurrentPages();
        var currentPage = pages[pages.length - 1];
        if (!currentPage) return;
        if (currentPage && currentPage.$vm.hasOwnProperty("receiveMessage")) {
          var rs = currentPage.$vm.receiveMessage(data);
          needpopup = !rs;
        }
        if (
          needpopup &&
          (data.type == "tokefu" ||
            data.type == "tokehu" ||
            data.type == "peisong" ||
            data.type == "notice")
        ) {
          // 需要弹窗提示
          currentPage.$vm.$refs.popmsg.open(data);
        }
      } catch (e) {}
    });
    //#endif
  },

  // 应用显示时的生命周期函数
  onShow: function (options) {
    var that = this;
    console.log("onShow");
    console.log(options);
    console.log("---------xxxx");

    // 处理场景值
    if (options && options.scene) {
      this.globalData.scene = options.scene;
      if (options.scene == 1154) {
        this.globalData.seetype = "circle"; // 查看类型为朋友圈
      }
    }

    // try {
    // 	// 获取启动时的场景值
    // 	const launchOptions = uni.getLaunchOptionsSync().scene;
    // 	// 1011-扫描二维码
    // 	if (launchOptions === 1001) {
    // 		if (uni.getLaunchOptionsSync().query.scene) {
    // 			let sr = this.parseCustomString(uni.getLaunchOptionsSync().query.scene);
    // 			if (sr) {
    // 				if (sr.pmid) {
    // 					this.globalData.pmid = sr.pmid;
    // 				}
    // 			}
    // 		}
    // 	}
    // } catch (error) {
    // }

    // 在微信小程序中处理分享卡片、订阅消息、扫码等场景
    // #ifdef MP-WEIXIN
    const sceneList = [
      1007, 1008, 1014, 1044, 1045, 1046, 1047, 1048, 1049, 1073, 1154, 1155,
    ];
    if (sceneList.includes(this.globalData.scene)) {
      console.log("---------00");
      try {
        let livePlayer = requirePlugin("live-player-plugin");
        console.log(livePlayer);
        console.log("---------11");
        livePlayer
          .getShareParams()
          .then((res) => {
            let custom_params = res.custom_params;
            console.log(custom_params);
            if (custom_params && custom_params.pid) {
              that.globalData.pid = custom_params.pid;
            }
          })
          .catch((err) => {
            console.log("get share params err ", err);
          });
      } catch (e) {
        console.log("live-player-plugin err ", e);
      }
    }
    // #endif

    // 如果mid和socket_token存在，则打开WebSocket连接
    //#ifndef MP-TOUTIAO
    if (that.globalData.mid && that.globalData.socket_token) {
      var app = this;
      app.openSocket();
    }
    //#endif
  },

  // 方法定义
  methods: {
    // 监听工具函数
    watchStatus: function (obj, key, callback) {
      let value = obj[key];
      Object.defineProperty(obj, key, {
        get() {
          return value;
        },
        set(newValue) {
          if (newValue !== value) {
            const oldValue = value;
            value = newValue;
            callback(newValue, oldValue);
          }
        },
      });

      // 返回解绑函数
      return () => {
        delete obj[key];
        obj[key] = value;
      };
    },

    //首页tab组件根据位置排序
    shortIndexTab: function (param) {
      // 如果数组为空，直接添加
      if (this.globalData.indexTab.length === 0) {
        this.globalData.indexTab.push(param);
        return;
      }

      if (this.globalData.indexTab.find((item) => item.id == param.id)) {
        return;
      }

      // 查找插入位置
      let inserted = false;
      for (let i = 0; i < this.globalData.indexTab.length; i++) {
        if (param.top < this.globalData.indexTab[i].top) {
          // 在当前位置插入
          this.globalData.indexTab.splice(i, 0, param);
          inserted = true;
          break;
        }
      }

      // 如果未插入，说明是最大的，添加到末尾
      if (!inserted) {
        this.globalData.indexTab.push(param);
      }

      // 输出排序后的数组
      // console.log('排序后的数组:', this.globalData.indexTab);
    },

    //设置tab组件加载状态
    setTabStatus: function (param) {
      if (this.globalData.tabList.length === 0) {
        return;
      }
      for (let i = 0; i < this.globalData.tabList.length; i++) {
        if (this.globalData.tabList[i].id === param) {
          this.globalData.tabList[i].status = true;
          return i;
        }
      }
    },

    // 判断是否为手机号
    isPhone: function (param) {
      var regExp = new RegExp("^1[35789]\\d{9}$");
      return regExp.test(param);
    },

    // 判断是否为身份证号
    isIdCard: function (param) {
      var regExp =
        /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
      return regExp.test(param);
    },

    // 解析启动参数 "key1_value1-key2_value2" 转换成数组形式
    getopts: function (opt) {
      console.log("解析启动参数: ", opt);
      if (opt && opt.scene) {
        var scene = opt.scene;
        var scenes = scene.split("-");
        var opts = {};
        for (var i in scenes) {
          var thisscenes = scenes[i].split("_");
          opts[thisscenes[0]] = thisscenes[1];
        }
        return opts;
      } else {
        return opt;
      }
    },

    // 显示提示框
    alert: function (content, confirmfun) {
      uni.showModal({
        title: "提示信息",
        showCancel: false,
        content: content.toString(),
        success: function (res) {
          if (res.confirm) {
            typeof confirmfun == "function" && confirmfun();
          }
        },
      });
    },

    // 显示确认框
    confirm: function (content, confirmfun, cancelfun) {
      uni.showModal({
        title: "操作确认",
        content: content.toString(),
        showCancel: true,
        success: function (res) {
          if (res.confirm) {
            typeof confirmfun == "function" && confirmfun();
          } else {
            typeof cancelfun == "function" && cancelfun();
          }
        },
      });
    },

    // 显示成功提示
    success: function (title, successfun) {
      if (undefined == title) title = "操作成功";
      var title = title.toString();
      uni.showToast({
        title: title,
        icon: title.length > 8 ? "none" : "success",
        success: function (res) {
          typeof successfun == "function" && successfun();
        },
      });
    },

    // 显示错误提示
    error: function (title, duration) {
      if (title === false) {
        uni.hideToast();
      } else {
        if (this.isNull(duration)) duration = 2500;
        if (undefined == title) title = "操作失败";
        uni.showToast({
          title: title.toString(),
          icon: "none",
          duration: duration,
        });
      }
    },

    // 显示加载中提示
    showLoading: function (title) {
      if (title === false) {
        uni.hideLoading();
        uni.stopPullDownRefresh(); // 停止下拉刷新
      } else {
        if (undefined == title) title = "加载中";
        if (title == "加载中") {
          this.showLoadingTime(15);
        }
        uni.showLoading({
          title: title.toString(),
          mask: true,
        });
      }
    },

    //定时关闭加载中提示
    showLoadingTime: function (time) {
      setTimeout(() => {
        this.showLoading(false);
      }, time * 1000);
    },

    // 判断数组中是否包含某个元素
    inArray: function (search, array) {
      for (var i in array) {
        if (array[i] == search) {
          return true;
        }
      }
      return false;
    },

    // 判断是否为空
    isNull: function (e) {
      return e == undefined || e == "undefined" || e == null || e == "";
    },

    // 解析JSON字符串
    parseJSON: function (e) {
      try {
        return JSON.parse(e);
      } catch (t) {
        return undefined;
      }
    },

    // 获取URL中的参数
    getparams: function (url) {
      if (url.indexOf("?") === -1) return {};
      var query = url.split("?")[1];
      var vars = query.split("&");
      var params = {};
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        params[pair[0]] = pair[1];
      }
      return params;
    },

    // 页面跳转
    goto: function (tourl, opentype) {
      var app = this;
      var params = app.getparams(tourl);
      console.log(params, tourl);

      // 如果参数中有reloadthispage，则重新加载当前页面
      if (params && params.reloadthispage == 1) {
        var thispage = getCurrentPages().pop();
        thispage.$vm.opt = params;
        thispage.$vm.getdata();
        return;
      }

      // 如果未指定opentype，则根据URL判断跳转方式
      if (app.isNull(opentype) && tourl) {
        var tablist = app.globalData.menudata["list"];
        if (tablist) {
          for (var i = 0; i < tablist.length; i++) {
            if (tablist[i]["pagePath"] == tourl) {
              opentype = "reLaunch";
            }
          }
        }
      }

      // 处理URL路径
      if (tourl.indexOf("pages/") === 0) tourl = "/" + tourl;
      if (tourl.indexOf("/pages/commission/") === 0)
        tourl = tourl.replace("/pages/commission/", "/activity/commission/");
      if (tourl.indexOf("/pages/sign/") === 0)
        tourl = tourl.replace("/pages/sign/", "/pagesExt/sign/");
      if (tourl.indexOf("/pages/business/") === 0)
        tourl = tourl.replace("/pages/business/", "/pagesExt/business/");
      if (tourl.indexOf("/pages/lipin/") === 0)
        tourl = tourl.replace("/pages/lipin/", "/pagesExt/lipin/");
      if (tourl.indexOf("/pages/order/") === 0)
        tourl = tourl.replace("/pages/order/", "/pagesExt/order/");
      if (
        tourl.indexOf("/pages/my/") === 0 &&
        tourl.indexOf("/pages/my/usercenter") !== 0
      )
        tourl = tourl.replace("/pages/my/", "/pagesExt/my/");

      // 如果是抖音平台且跳转到商品页面，则处理抖音商品ID
      if (
        app.globalData.isdouyin == 1 &&
        tourl.indexOf("/pages/shop/product") === 0
      ) {
        app.showLoading("加载中");
        app.post(
          "Shop/getDouyinProductId",
          {
            proid: params.id,
          },
          function (res) {
            app.showLoading(false);
            if (res.status == 1) {
              tt.openEcGood({
                promotionId: res.douyin_product_id,
                fail: function (res2) {
                  app.alert(res2.errMsg);
                },
              });
            } else {
              app.alert(res.msg);
            }
          }
        );
        return;
      }

      // 如果是微信平台且跳转到客服页面，则打开微信客服
      if (
        app.globalData.platform == "wx" &&
        tourl.indexOf("https://work.weixin.qq.com/kfid/") === 0
      ) {
        wx.openCustomerServiceChat({
          extInfo: {
            url: tourl,
          },
          corpId: app.globalData.initdata.corpid,
        });
        return;
      }

      // 处理扫码功能
      if (tourl == "scan::") {
        if (app.globalData.platform == "h5") {
          app.alert("请使用微信扫一扫功能扫码");
          return;
        } else if (app.globalData.platform == "mp") {
          var jweixin = require("jweixin-module");
          jweixin.ready(function () {
            jweixin.scanQRCode({
              needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
              scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
              success: function (res) {
                var content = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                // app.goto(content);
              },
            });
          });
        } else {
          uni.scanCode({
            success: function (res) {
              console.log(res);
              if (res.path) {
                app.goto("/" + res.path);
              } else {
                var content = res.result;
                app.goto(content);
              }
            },
          });
        }
        return;
      }

      // 处理分享功能
      if (tourl == "share::") {
        if (
          app.globalData.platform == "h5" ||
          app.globalData.platform == "mp"
        ) {
          app.error("点击右上角发送给好友或分享到朋友圈");
        }
        if (app.globalData.platform == "app") {
          uni.showActionSheet({
            itemList: ["发送给微信好友", "分享到微信朋友圈"],
            success: function (res) {
              if (res.tapIndex >= 0) {
                var scene = "WXSceneSession";
                if (res.tapIndex == 1) {
                  scene = "WXSenceTimeline";
                }
                var sharedata = {};
                sharedata.provider = "weixin";
                sharedata.type = 0;
                sharedata.scene = scene;
                sharedata.title = app.globalData.initdata.name;
                var fullurl = app._fullurl();
                if (app.globalData.mid > 0) {
                  fullurl +=
                    (fullurl.indexOf("?") === -1 ? "?" : "&") +
                    "pid=" +
                    app.globalData.mid;
                }
                sharedata.href =
                  app.globalData.pre_url +
                  "/h5/" +
                  app.globalData.aid +
                  ".html#" +
                  fullurl;
                sharedata.imageUrl = app.globalData.initdata.logo;
                sharedata.summary = app.globalData.initdata.desc;

                var sharelist = app.globalData.initdata.sharelist;
                if (sharelist) {
                  for (var i = 0; i < sharelist.length; i++) {
                    if (sharelist[i]["indexurl"] == app._fullurl()) {
                      sharedata.title = sharelist[i].title;
                      sharedata.summary = sharelist[i].desc;
                      sharedata.imageUrl = sharelist[i].pic;
                      if (sharelist[i].url) {
                        var sharelink = sharelist[i].url;
                        if (sharelink.indexOf("/") === 0) {
                          sharelink =
                            app.globalData.pre_url +
                            "/h5/" +
                            app.globalData.aid +
                            ".html#" +
                            sharelink;
                        }
                        if (app.globalData.mid > 0) {
                          sharelink +=
                            (sharelink.indexOf("?") === -1 ? "?" : "&") +
                            "pid=" +
                            app.globalData.mid;
                        }
                        sharedata.href = sharelink;
                      }
                    }
                  }
                }
                uni.share(sharedata);
              }
            },
          });
        }
        return;
      }

      // 处理电话拨打功能
      if (tourl.indexOf("tel::") === 0) {
        tourl = tourl.slice(5);
        uni.makePhoneCall({
          phoneNumber: tourl,
        });
        return;
      }

      // 处理外部链接跳转
      if (tourl.indexOf("url::") === 0) {
        if (
          app.globalData.platform == "h5" ||
          app.globalData.platform == "mp"
        ) {
          location.href = tourl.slice(5);
        } else {
          tourl =
            "/pages/index/webView?url=" + encodeURIComponent(tourl.slice(5));
        }
      }

      // 处理外部链接跳转（带参数）
      if (tourl.indexOf("https://") === 0 || tourl.indexOf("http://") === 0) {
        tourl +=
          (tourl.indexOf("?") > 0 ? "&" : "?") +
          "yiyang_aid=" +
          app.globalData.aid +
          "&yiyang_mid=" +
          app.globalData.mid;
        if (
          app.globalData.platform == "h5" ||
          app.globalData.platform == "mp"
        ) {
          location.href = tourl;
        } else {
          tourl = "/pages/index/webView?url=" + encodeURIComponent(tourl);
        }
      }

      // 处理跳转到其他小程序
      if (tourl.indexOf("miniProgram::") === 0) {
        tourl = tourl.slice(13);
        var tourlArr = tourl.split("|");
        if (app.globalData.platform == "app") {
          plus.share.getServices(
            function (res) {
              var sweixin = null;
              for (var i = 0; i < res.length; i++) {
                var t = res[i];
                if (t.id == "weixin") {
                  sweixin = t;
                }
              }
              if (sweixin) {
                sweixin.launchMiniProgram({
                  id: tourlArr[2],
                  type: 0,
                  path: tourlArr[1] ? tourlArr[1] : "",
                });
              }
            },
            function (res) {
              console.log(JSON.stringify(res));
            }
          );
        } else {
          uni.navigateToMiniProgram({
            appId: tourlArr[0],
            path: tourlArr[1] ? tourlArr[1] : "",
            complete: function () {
              if (tourlArr[2]) {
                app.goto(tourlArr[2]);
              }
            },
          });
        }
        return;
      }

      // 处理坐标导航功能
      if (tourl.indexOf("location::") === 0) {
        tourl = tourl.slice(10);
        var tourlArr = tourl.split("|");
        var jwd = tourlArr[1].split(",");
        uni.openLocation({
          latitude: parseFloat(jwd[1]),
          longitude: parseFloat(jwd[0]),
          name: tourlArr[0],
          scale: 13,
        });
        return;
      }

      // 处理小程序直播功能
      if (
        tourl.indexOf(
          "plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin"
        ) === 0
      ) {
        tourl =
          tourl +
          "&custom_params=" +
          encodeURIComponent(
            JSON.stringify({
              pid: app.globalData.mid,
            })
          );
      }

      // 处理复制功能
      if (tourl.indexOf("copy::") === 0) {
        tourl = tourl.slice(6);
        var tourlArr = tourl.split("|");
        uni.setClipboardData({
          data: tourlArr[0],
          showToast: false,
          success: function () {
            if (tourlArr[1] != "复制成功") app.alert(tourlArr[1]);
            else if (tourlArr[1]) app.error(tourlArr[1]);
          },
        });
        return;
      }

      // 根据opentype执行不同的跳转方式
      if (app.isNull(opentype)) {
        var mv = tourl.split("?");
        var urlpath = mv[0];
        if (app.globalData.platform == "h5" && urlpath == app._fullurl()) {
          opentype = "reLaunch";
        } else {
          opentype = "navigate";
        }
      }

      app.globalData.rewardedVideoAd = {};

      // 执行跳转
      if (opentype == "switchTab") {
        var args = new Object();
        var name, value;
        var url = tourl;
        var num = url.indexOf("?");
        if (num >= 0) {
          var urlbase = url.substr(0, num);
          var str = url.substr(num + 1);
          var arr = str.split("&");
          for (var i = 0; i < arr.length; i++) {
            num = arr[i].indexOf("=");
            if (num > 0) {
              name = arr[i].substring(0, num);
              value = arr[i].substr(num + 1);
              args[name] = value;
            }
          }
          uni.switchTab({
            url: urlbase,
            success: function (e) {
              var page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.onLoad(args);
            },
          });
        } else {
          uni.switchTab({
            url: tourl,
          });
        }
      } else if (opentype == "redirect" || opentype == "redirectTo") {
        uni.redirectTo({
          url: tourl,
        });
      } else if (opentype == "reLaunch") {
        uni.reLaunch({
          url: tourl,
        });
      } else {
        var pages = getCurrentPages();
        if (pages.length >= 10) {
          uni.redirectTo({
            url: tourl,
          });
        } else {
          uni.navigateTo({
            url: tourl,
          });
        }
      }
    },

    // 返回上一页
    goback: function (isreload) {
      var app = this;
      var pages = getCurrentPages();
      if (isreload && pages.length > 1) {
        var prePage = pages[pages.length - 2];
        prePage.$vm.getdata();
      }
      if (pages.length == 1) {
        app.goto(app.globalData.indexurl, "reLaunch");
      } else {
        uni.navigateBack({
          fail: function () {
            app.goto(app.globalData.indexurl, "reLaunch");
          },
        });
      }
    },

    // 发送POST请求
    post: function (url, param, callback) {
      this.request("POST", url, param, callback);
    },

    // 发送GET请求
    get: function (url, param, callback) {
      this.request("GET", url, param, callback);
    },

    // 发送HTTP请求
    request: function (method, url, param, callback) {
      console.log("请求url：", url);
      var oldurl = url;
      var app = this;
      if (url.substring(0, 8) != "https://") {
        url = app.globalData.baseurl + url;
        url +=
          (url.indexOf("?") > 0 ? "&" : "?") +
          "aid=" +
          app.globalData.aid +
          "&platform=" +
          app.globalData.platform +
          "&session_id=" +
          app.globalData.session_id +
          "&pid=" +
          app.globalData.pid;
        if (app.globalData.isdouyin == 1) {
          url += "&isdouyin=1";
        }
        if (!app.globalData.isinit) {
          url += "&needinit=1";
          if (app.globalData.uid) url += "&uid=" + app.globalData.uid;
        }
        if (app.globalData.seetype) {
          url += "&seetype=" + app.globalData.seetype;
        }
        if (app.globalData.scene) {
          url += "&scene=" + app.globalData.scene;
        }
      }
      uni.request({
        url: url,
        data: param,
        method: method,
        success: function (res) {
          app.setinitdata(res);
          if (url == "Index/logout" && res.data.status == -3) {
            // app.globalData.mid = 0;
            uni.setStorageSync("mid", 0);
            console.log("用户id清0", app.globalData.mid);
          }
          if (res.data && res.data.status == -1) {
            // 跳转登录页
            app.showLoading(false);
            if (
              app.globalData.initdata.logintype.length == 0 &&
              app.inArray(app.globalData.platform, [
                "wx",
                "mp",
                "baidu",
                "qq",
                "toutiao",
                "alipay",
              ])
            )
              return;
            var pages = getCurrentPages();
            var currentPage = pages[pages.length - 1];
            currentPage.$vm.loading = false;
            var frompage = "";
            var nowurl = app._url();
            var opentype = "reLaunch";
            if (app.globalData.platform == "baidu") {
              if (nowurl == "/pages/my/usercenter") {
                opentype = "redirect";
              } else {
                opentype = "navigate";
              }
            }
            if (
              nowurl != "/pages/index/login" &&
              nowurl != "/pages/index/reg" &&
              nowurl != "/pages/index/getpwd"
            ) {
              var frompage = encodeURIComponent(app._fullurl());
            }
            if (res.data.authlogin == 1) {
              app.authlogin(function (res2) {
                if (res2.status == 1) {
                  if (res2.msg) app.success(res2.msg);
                  currentPage.$vm.getdata();
                } else if (res2.status == 2) {
                  app.goto(
                    "/pages/index/login?frompage=" +
                      frompage +
                      "&logintype=4&login_bind=1",
                    opentype
                  );
                } else {
                  console.log("app.authlogin-else:", res2);
                  app.goto("/pages/index/login?frompage=" + frompage, opentype);
                }
              });
            } else {
              app.goto("/pages/index/login?frompage=" + frompage, opentype);
              return;
            }
          } else if (res.data && res.data.status == -10) {
            // 跳转管理员登录
            app.showLoading(false);
            var pages = getCurrentPages();
            var currentPage = pages[pages.length - 1];
            currentPage.$vm.loading = false;
            app.goto("/admin/index/login", "redirect");
          } else if (res.data && res.data.status == -2) {
            // 公众号或H5跳转
            app.showLoading(false);
            var pages = getCurrentPages();
            var currentPage = pages[pages.length - 1];
            currentPage.$vm.loading = false;
            location.href = res.data.url;
          } else if (res.data && res.data.status == -3) {
            // 跳转到指定页
            app.showLoading(false);
            var pages = getCurrentPages();
            var currentPage = pages[pages.length - 1];
            currentPage.$vm.loading = false;
            app.goto(res.data.url, "redirect");
          } else if (res.data && res.data.status == -4) {
            // 弹窗提示并跳转到指定页
            app.showLoading(false);
            var pages = getCurrentPages();
            var currentPage = pages[pages.length - 1];
            currentPage.$vm.loading = false;
            app.alert(res.data.msg, function () {
              if (res.data.url) {
                app.goto(res.data.url, "redirect");
              }
            });
          } else {
            typeof callback == "function" && callback(res.data);
          }
        },
        fail: function (res) {
          try {
            if (oldurl != "Index/linked") {
              if (res.errMsg != "request:fail timeout") {
                console.log("接口异常", res);
              }
            }
          } catch (e) {
          } finally {
            app.showLoading(false);
            console.log("接口异常:" + res.errMsg);
            // uni.showToast({
            // 	title: "接口异常:" + res.errMsg,
            // 	icon: "none",
            // 	duration: 2500,
            // });
          }
        },
      });
    },

    // 基础登录
    baselogin: function (callback) {
      console.log("baselogin");
      var app = this;
      if (app.globalData.platform == "wx") {
        wx.login({
          success(res1) {
            var code = res1.code;
            app.post(
              "Index/wxbaselogin",
              {
                code: code,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          },
        });
      } else if (app.globalData.platform == "baidu") {
        swan.getLoginCode({
          success(res1) {
            console.log(res1);
            var code = res1.code;
            app.post(
              "Index/baidulogin",
              {
                code: code,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          },
          fail(res2) {
            console.log(res2);
          },
        });
      } else if (app.globalData.platform == "qq") {
        qq.login({
          success(res1) {
            app.post(
              "Index/qqlogin",
              {
                code: res1.code,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          },
        });
      } else if (app.globalData.platform == "toutiao") {
        tt.login({
          force: true,
          success(res1) {
            app.post(
              "Index/toutiaologin",
              {
                code: res1.code,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          },
        });
      } else if (app.globalData.platform == "alipay") {
        my.getAuthCode({
          scopes: "auth_base",
          success(res1) {
            app.post(
              "Index/alipaylogin",
              {
                code: res1.authCode,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          },
        });
      } else if (app.globalData.platform == "mp") {
        var frompage = "";
        var nowurl = app._url();
        if (
          nowurl != "/pages/index/login" &&
          nowurl != "/pages/index/reg" &&
          nowurl != "/pages/index/getpwd"
        ) {
          frompage = encodeURIComponent(app._fullurl());
        }
        location.href =
          app.globalData.api_url +
          "/Index/mpbaselogin&aid=" +
          app.globalData.aid +
          "&session_id=" +
          app.globalData.session_id +
          "&pid=" +
          app.globalData.pid +
          "&frompage=" +
          encodeURIComponent(frompage);
      }
    },

    // 授权登录
    authlogin: function (callback, params) {
      var app = this;
      if (app.globalData.platform == "wx") {
        wx.getUserProfile({
          lang: "zh_CN",
          desc: "用于展示头像昵称",
          success: function (res2) {
            console.log(res2);
            var userinfo = res2.userInfo;
            wx.login({
              success(res1) {
                var code = res1.code;
                app.post(
                  "Index/wxlogin",
                  {
                    code: code,
                    userinfo: userinfo,
                    pid: app.globalData.pid,
                    yqcode: params ? params.yqcode : null,
                  },
                  function (res) {
                    if (res.status == 1) {
                      uni.setStorageSync("mid", res.mid);
                    }
                    typeof callback == "function" && callback(res);
                  }
                );
              },
            });
          },
          fail: function (res2) {
            console.log(res2);
            if (res2.errMsg == "getUserProfile:fail auth deny") {
              // 用户拒绝授权
            } else {
              typeof callback == "function" &&
                callback({
                  status: 0,
                  msg: res2.errMsg,
                });
            }
          },
        });
      } else if (
        app.globalData.platform == "mp" ||
        app.globalData.platform == "h5"
      ) {
        var frompage = "";
        var nowurl = app._url();
        if (
          nowurl != "/pages/index/login" &&
          nowurl != "/pages/index/reg" &&
          nowurl != "/pages/index/getpwd"
        ) {
          frompage = encodeURIComponent(app._fullurl());
        }
        if (params && params.frompage) {
          frompage = params.frompage;
        }
        location.href =
          app.globalData.api_url +
          "Index/shouquan&aid=" +
          app.globalData.aid +
          "&session_id=" +
          app.globalData.session_id +
          "&pid=" +
          app.globalData.pid +
          "&frompage=" +
          encodeURIComponent(frompage);
      } else if (app.globalData.platform == "app") {
        plus.oauth.getServices(function (services) {
          console.log(services);
          let s = services[0];
          for (var i in services) {
            var service = services[i];
            if (service.id == "weixin") {
              s = service;
            }
          }
          console.log(s);
          console.log("x----");
          s.authorize(function (e) {
            console.log(e);
            var code = e.code;
            app.post(
              "Index/appwxlogin",
              {
                code: code,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          });
        });
      } else if (app.globalData.platform == "baidu") {
        swan.getLoginCode({
          success: (res) => {
            console.log("getLoginCode success", res);
            var code = res.code;
            app.post(
              "Index/baidulogin",
              {
                code: code,
                pid: app.globalData.pid,
              },
              function (res) {
                typeof callback == "function" && callback(res);
              }
            );
          },
          fail: (err) => {
            typeof callback == "function" &&
              callback({
                status: 0,
                msg: err.errMsg,
              });
          },
        });
      } else if (app.globalData.platform == "qq") {
        qq.login({
          success(res) {
            if (res.code) {
              app.post(
                "Index/qqlogin",
                {
                  code: res.code,
                  pid: app.globalData.pid,
                },
                function (res) {
                  typeof callback == "function" && callback(res);
                }
              );
            } else {
              typeof callback == "function" &&
                callback({
                  status: 0,
                  msg: res.errMsg,
                });
            }
          },
          fail(res) {
            typeof callback == "function" &&
              callback({
                status: 0,
                msg: res.errMsg,
              });
          },
        });
      } else if (app.globalData.platform == "toutiao") {
        tt.login({
          force: true,
          success(res) {
            if (res.code) {
              app.post(
                "Index/toutiaologin",
                {
                  code: res.code,
                  pid: app.globalData.pid,
                },
                function (res) {
                  typeof callback == "function" && callback(res);
                }
              );
            } else {
              typeof callback == "function" &&
                callback({
                  status: 0,
                  msg: res.errMsg,
                });
            }
          },
          fail(res) {
            typeof callback == "function" &&
              callback({
                status: 0,
                msg: res.errMsg,
              });
          },
        });
      } else if (app.globalData.platform == "alipay") {
        my.getAuthCode({
          scopes: "auth_base",
          success: (res) => {
            console.log(res);
            if (res.authCode) {
              app.post(
                "Index/alipaylogin",
                {
                  code: res.authCode,
                  pid: app.globalData.pid,
                },
                function (res) {
                  typeof callback == "function" && callback(res);
                }
              );
            }
          },
          fail: (res) => {
            typeof callback == "function" &&
              callback({
                status: 0,
                msg: res.errMsg,
              });
          },
        });
      }
    },

    // 设置初始化数据
    setinitdata: function (res) {
      var app = this;
      var oldmid = app.globalData.mid;
      if (
        res &&
        res.data &&
        (res.data.mid || res.data.mid === 0) &&
        app.globalData.mid != res.data.mid
      ) {
        app.globalData.mid = res.data.mid;
        uni.setStorageSync("mid", app.globalData.mid);
        if (res.data.session_id) {
          uni.setStorageSync("session_id", res.data.session_id);
          app.globalData.session_id = res.data.session_id;
        }
        if (app.globalData.mid) {
          app.globalData.socket_token = res.data.socket_token;
          app.openSocket();
          uni.removeStorageSync("pid");
        }
      }
      if (res && res.data && res.data._initdata) {
        app.globalData.isinit = true;
        res.data._initdata.pre_url = app.globalData.pre_url;
        app.globalData.initdata = res.data._initdata;
        app.globalData.mid = res.data._initdata.mid;
        uni.setStorageSync("mid", app.globalData.mid);
        app.globalData.isdouyin = res.data._initdata.isdouyin;
        uni.setStorageSync("session_id", res.data._initdata.session_id);
        app.globalData.session_id = res.data._initdata.session_id;
        const mockConfig = {
          frontColor: "#ffffff",
          backgroundColor: res.data._initdata.color1, // 动态颜色
        };
        uni.setStorageSync("navConfig", mockConfig);
        if (app.globalData.platform == "mp") {
          var share_package = res.data.share_package;
          var jweixin = require("jweixin-module");
          jweixin.config({
            debug: false,
            appId: share_package.appId,
            timestamp: share_package.timestamp,
            nonceStr: share_package.nonceStr,
            signature: share_package.signature,
            jsApiList: [
              "checkJsApi",
              "onMenuShareAppMessage",
              "onMenuShareTimeline",
              "updateAppMessageShareData",
              "updateTimelineShareData",
              "chooseImage",
              "previewImage",
              "uploadImage",
              "openLocation",
              "getLocation",
              "closeWindow",
              "scanQRCode",
              "chooseWXPay",
              "addCard",
              "chooseCard",
              "openCard",
            ],
            openTagList: ["wx-open-launch-weapp"],
          });
        }
        if (app.globalData.mid) {
          app.globalData.socket_token = res.data.socket_token;
          app.openSocket();
          uni.removeStorageSync("pid");
        }
        if (
          !app.globalData.mid &&
          app.globalData.initdata.logintype.length == 0
        ) {
          app.baselogin(function (res2) {
            var pages = getCurrentPages();
            var currentPage = pages[pages.length - 1];
            var url =
              "/" +
              (currentPage.route ? currentPage.route : currentPage.__route__);
            if (url == "/pages/index/login") {
              if (app.globalData.platform == "baidu") {
                var opts = currentPage.options;
              } else {
                var opts = currentPage.$vm.opt;
              }
              console.log(opts);
              if (opts && opts.frompage) {
                app.goto(decodeURIComponent(opts.frompage), "redirect");
              } else {
                app.goto("/pages/my/usercenter", "redirect");
              }
            } else {
              currentPage.$vm.getdata();
            }
          });
        }
        console.log("system_fontsystem_font", res.data._initdata.system_font);
        if (res.data._initdata.system_font) {
          // #ifdef MP-WEIXIN
          wx.loadFontFace({
            family: "CustomFont",
            global: true,
            // source: "https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250403/318b41438cd576467d5d67fbcb9641e9.OTF",
            source: res.data._initdata.system_font,
            success: () => {
              console.log({
                title: "字体加载成功",
              });
            },
            fail: (err) => {
              console.error("字体加载失败", err);
              // uni.showToast({ title: '字体加载失败', icon: 'none' });
            },
          });
          // #endif
        }
      }
      if (app.globalData.mid && app.globalData.mid != oldmid) {
        if (app.globalData.platform == "wx") {
          wx.login({
            success: function (res) {
              if (res.code) {
                app.post(
                  "Index/setwxopenid",
                  {
                    code: res.code,
                  },
                  function () {}
                );
              }
            },
          });
        } else if (app.globalData.platform == "alipay") {
          my.getAuthCode({
            scopes: ["auth_base"],
            success: (res) => {
              if (res.authCode) {
                app.post(
                  "Index/setalipayopenid",
                  {
                    code: res.authCode,
                  },
                  function () {}
                );
              }
            },
          });
        } else if (app.globalData.platform == "baidu") {
          swan.getLoginCode({
            success: (res) => {
              if (res.code) {
                app.post(
                  "Index/setbaiduopenid",
                  {
                    code: res.code,
                  },
                  function () {}
                );
              }
            },
            fail: (err) => {
              console.log("getLoginCode fail", err);
            },
          });
        }
      }
    },

    // 启用WebSocket连接
    openSocket: function () {
      console.log("openSocket");
      //#ifndef MP-TOUTIAO
      var app = this;
      app.globalData.socketOpen = false;
      uni.closeSocket();
      uni.connectSocket({
        url: app.globalData.pre_url.replace("https://", "wss://") + "/wss",
      });
      app.sendSocketMessage({
        type: "auth",
      });
      clearInterval(app.globalData.socketInterval);
      app.globalData.socketInterval = setInterval(function () {
        app.sendSocketMessage({
          type: "heartbat",
        });
      }, 30000);
      //#endif
    },

    // 发送WebSocket消息
    sendSocketMessage: function (msg) {
      var app = this;
      if (!msg.token) msg.token = this.globalData.socket_token;
      if (!msg.aid) msg.aid = this.globalData.aid;
      if (!msg.session_id) msg.session_id = this.globalData.session_id;
      if (app.globalData.socketOpen) {
        console.log(msg);
        uni.sendSocketMessage({
          data: JSON.stringify(msg),
          fail: function (res) {
            console.log(res);
            console.log("发送失败");
            if (app.globalData.socketConnecttimes < 1) {
              app.globalData.socketConnecttimes++;
              app.globalData.socketMsgQueue.push(msg);
              console.log("openSocket 重连");
              app.openSocket();
            }
          },
          success: function () {
            console.log("发送成功");
            app.globalData.socketConnecttimes = 0;
          },
        });
      } else {
        this.globalData.socketMsgQueue.push(msg);
      }
    },

    // 处理WebSocket消息
    handleSocketMessage: function (data) {
      var app = this;
      if (data.hasOwnProperty("status")) {
        if (data.status != 200) {
          console.log("ws数据异常：" + data.msg);
        } else {
          uni.$emit("socketMessage-api", data);
        }
      }

      if (data.hasOwnProperty("code")) {
        if (data.code != 200) {
          console.log("ws数据异常：" + data.msg);
        } else {
          uni.$emit("socketMessage-api", data);
        }
      }
    },

    // 选择图片
    chooseImage: function (callback, count) {
      var app = this;
      uni.chooseImage({
        count: count || 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: function (res) {
          var tempFilePaths = res.tempFilePaths,
            imageUrls = [];
          for (var i = 0; i < tempFilePaths.length; i++) {
            app.showLoading("上传中");
            uni.uploadFile({
              url:
                app.globalData.baseurl +
                "Imageupload/uploadImg/aid/" +
                app.globalData.aid +
                "/platform/" +
                app.globalData.platform +
                "/session_id/" +
                app.globalData.session_id,
              filePath: tempFilePaths[i],
              name: "file",
              success: function (res) {
                app.showLoading(false);
                if (typeof res.data == "string") {
                  var data = JSON.parse(res.data);
                } else {
                  var data = res.data;
                }
                if (data.status == 1) {
                  imageUrls.push(data.url);
                  if (imageUrls.length == tempFilePaths.length) {
                    typeof callback == "function" && callback(imageUrls);
                  }
                } else {
                  app.alert(data.msg);
                }
              },
              fail: function (res) {
                app.showLoading(false);
                app.alert(res.errMsg);
              },
            });
          }
        },
        fail: function (res) {
          // alert(res.errMsg);
        },
      });
    },

    // 选择相册视频
    chooseAlbumVideo: function (callback, count) {
      var app = this;
      uni.chooseMedia({
        count: count || 1,
        mediaType: ["video"],
        sourceType: ["album"],
        success: function (res) {
          var tempFilePaths = res.tempFiles,
            imageUrls = [];
          for (var i = 0; i < tempFilePaths.length; i++) {
            app.showLoading("上传中");
            uni.uploadFile({
              url:
                app.globalData.baseurl +
                "Imageupload/uploadImg/aid/" +
                app.globalData.aid +
                "/platform/" +
                app.globalData.platform +
                "/session_id/" +
                app.globalData.session_id,
              filePath: tempFilePaths[i].tempFilePath,
              name: "file",
              success: function (res) {
                app.showLoading(false);
                if (typeof res.data == "string") {
                  var data = JSON.parse(res.data);
                } else {
                  var data = res.data;
                }
                if (data.status == 1) {
                  imageUrls.push({
                    url: data.url,
                    extend: data.info,
                  });
                  if (imageUrls.length == tempFilePaths.length) {
                    typeof callback == "function" && callback(imageUrls);
                  }
                } else {
                  app.alert(data.msg);
                }
              },
              fail: function (res) {
                app.showLoading(false);
                app.alert(res.errMsg);
              },
            });
          }
        },
        fail: function (res) {
          // alert(res.errMsg);
        },
      });
    },

    //选择拍摄视频
    chooseVideo: function (callback, count, maxDuration) {
      var app = this;
      uni.chooseMedia({
        count: count || 1,
        mediaType: ["video"],
        sourceType: ["camera"],
        maxDuration: maxDuration || 30, // 视频最大时长（秒）
        success: function (res) {
          var tempFilePaths = res.tempFiles,
            imageUrls = [];
          for (var i = 0; i < tempFilePaths.length; i++) {
            app.showLoading("上传中");
            uni.uploadFile({
              url:
                app.globalData.baseurl +
                "Imageupload/uploadImg/aid/" +
                app.globalData.aid +
                "/platform/" +
                app.globalData.platform +
                "/session_id/" +
                app.globalData.session_id,
              filePath: tempFilePaths[i].tempFilePath,
              name: "file",
              success: function (res) {
                app.showLoading(false);
                if (typeof res.data == "string") {
                  var data = JSON.parse(res.data);
                } else {
                  var data = res.data;
                }
                if (data.status == 1) {
                  imageUrls.push({
                    url: data.url,
                    extend: data.info,
                  });
                  if (imageUrls.length == tempFilePaths.length) {
                    typeof callback == "function" && callback(imageUrls);
                  }
                } else {
                  app.alert(data.msg);
                }
              },
              fail: function (res) {
                app.showLoading(false);
                app.alert(res.errMsg);
              },
            });
          }
        },
        fail: function (res) {
          // alert(res.errMsg);
        },
      });
    },

    // 获取地理位置
    getLocation: function (callback1, callback2) {
      var that = this;
      if (this.globalData.platform == "mp") {
        var jweixin = require("jweixin-module");
        jweixin.ready(function () {
          jweixin.getLocation({
            type: "gcj02",
            success: function (res) {
              that.setCache("getLocationCatch", res);
              typeof callback1 == "function" && callback1(res);
            },
            fail: function (res) {
              var locationCatch = that.getCache("getLocationCatch");
              if (locationCatch) {
                typeof callback1 == "function" && callback1(locationCatch);
              } else {
                typeof callback2 == "function" && callback2(res);
              }
            },
          });
        });
      } else if (this.globalData.platform == "alipay") {
        uni.getLocation({
          success: function (res) {
            that.setCache("getLocationCatch", res);
            typeof callback1 == "function" && callback1(res);
          },
          fail: function (res) {
            var locationCatch = that.getCache("getLocationCatch");
            if (locationCatch) {
              typeof callback1 == "function" && callback1(locationCatch);
            } else {
              typeof callback2 == "function" && callback2(res);
            }
          },
        });
      } else {
        uni.getLocation({
          type: "gcj02",
          success: function (res) {
            that.setCache("getLocationCatch", res);
            typeof callback1 == "function" && callback1(res);
          },
          fail: function (res) {
            var locationCatch = that.getCache("getLocationCatch");
            if (locationCatch) {
              typeof callback1 == "function" && callback1(locationCatch);
            } else {
              typeof callback2 == "function" && callback2(res);
            }
          },
        });
      }
    },

    // 设置缓存
    setCache: function (key, value, expire_time) {
      if (!expire_time) {
        expire_time = 0;
      }
      var expire_time = parseInt(expire_time);
      if (expire_time > 0) {
        var curtime = new Date().getTime();
        uni.setStorageSync(key + "_expiretime_second", expire_time * 60 * 1000);
        uni.setStorageSync(
          key + "_expiretime",
          curtime + expire_time * 60 * 1000
        );
      }
      return uni.setStorageSync(key, value);
    },

    // 获取缓存
    getCache: function (key) {
      var app = this;
      var cacheVal = uni.getStorageSync(key);
      if (cacheVal) {
        var expirekey = key + "_expiretime";
        var expiretime = uni.getStorageSync(expirekey);
        if (expiretime) {
          expiretime = parseInt(expiretime);
          var curtime = new Date().getTime();
          console.log("ct:" + curtime);
          console.log("et:" + expiretime);
          if (expiretime < curtime) {
            console.log("过期");
            app.removeCache(key);
            app.removeCache(expirekey);
            return "";
          } else {
            console.log("未过期");
            var cacheSecond = parseInt(
              uni.getStorageSync(key + "_expiretime_second")
            );
            app.setCache(expirekey, curtime + cacheSecond);
            return uni.getStorageSync(key);
          }
        } else {
          return cacheVal;
        }
      }
      return cacheVal;
    },

    // 移除缓存
    removeCache: function (key) {
      var $ = this;
      if ($.isNull(key)) {
        uni.clearStorageSync();
      } else {
        uni.removeStorageSync(key);
        uni.removeStorageSync(key + "_expiretime");
      }
    },

    // 获取当前页面的URL
    _url: function () {
      var pages = getCurrentPages();
      var currentPage = pages[pages.length - 1];
      var url =
        "/" + (currentPage.route ? currentPage.route : currentPage.__route__);
      return url;
    },

    // 获取当前页面的完整URL（带参数）
    _fullurl: function () {
      var pages = getCurrentPages();
      var currentPage = pages[pages.length - 1];
      var url =
        "/" + (currentPage.route ? currentPage.route : currentPage.__route__);
      if (this.globalData.platform == "baidu") {
        var opts = currentPage.options;
      } else {
        var opts = currentPage.$vm.opt;
      }
      console.log(opts);
      var params = [];
      for (var i in opts) {
        params.push(i + "=" + opts[i]);
      }
      if (params.length > 0) {
        url += "?" + params.join("&");
      }
      console.log(url);
      return url;
    },

    // 检查微信小程序版本更新
    // checkUpdateVersion() {
    // 	if (wx.canIUse('getUpdateManager')) {
    // 		const updateManager = wx.getUpdateManager();
    // 		updateManager.onCheckForUpdate(function (res) {
    // 			if (res.hasUpdate) {
    // 				updateManager.onUpdateReady(function () {
    // 					updateManager.applyUpdate();
    // 				});
    // 				updateManager.onUpdateFailed(function () {
    // 					// 新版本下载失败
    // 				});
    // 			}
    // 		});
    // 	} else {
    // 		// 微信版本过低
    // 	}
    // }
    checkUpdateVersion() {
      if (wx.canIUse("getUpdateManager")) {
        const updateManager = wx.getUpdateManager();

        // 检查是否有新版本
        updateManager.onCheckForUpdate((res) => {
          if (res.hasUpdate) {
            console.log("检测到新版本，开始下载");
            // 新版本下载完成
            updateManager.onUpdateReady(() => {
              uni.showModal({
                title: "更新提示",
                content: "新版本已准备好，是否立即重启应用？",
                success: (res) => {
                  if (res.confirm) {
                    // 应用新版本并重启
                    updateManager.applyUpdate();
                  }
                },
              });
            });

            // 新版本下载失败
            updateManager.onUpdateFailed(() => {
              uni.showToast({
                title: "新版本下载失败，请检查网络",
                icon: "none",
              });
            });
          } else {
            console.log("当前已是最新版本");
          }
        });
      } else {
        // 微信版本过低，提示用户升级微信
        uni.showModal({
          title: "提示",
          content: "当前微信版本过低，请升级到最新版本",
          showCancel: false,
        });
      }
    },
    parseCustomString(str) {
      // 1. 按 "-" 分割字符串，得到属性值对数组
      const pairs = str.split("-");
      const result = {};

      for (const pair of pairs) {
        // 2. 过滤空字符串（避免末尾多余的 "-"）
        if (!pair.trim()) continue;

        // 3. 按第一个 "_" 分割属性和值（避免值中有下划线）
        const index = pair.indexOf("_");
        if (index === -1) {
          console.warn(`无效格式: ${pair}`);
          continue;
        }

        const key = pair.slice(0, index).trim();
        const value = pair.slice(index + 1).trim();

        // 4. 存入结果对象
        if (key) {
          result[key] = value || null; // 若无值则设为 null
        }
      }
      return result;
    },
  },
};
</script>

<style>
@import "./common.css";
@import "./iconfont.css";
@import "@/components/parse/parse.css";

/* 全局字体设置 */
page,
.custom-font {
  font-family: "CustomFont", -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, Helvetica, Arial, sans-serif;
}
</style>
